// pages/search/search.js
import {
    areaList
} from '../../miniprogram_npm/miniprogram_npm/@vant/area-data/index'
import Toast from '../../miniprogram_npm/miniprogram_npm/@vant/weapp/toast/toast'

const app = getApp() // 获取全局APP对象

Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 弹出操作控
        showCityPicker: false,
        areaList,
        pickCity: '全国',
        curCity: '未知',
        curCityNum: 110101,
        isGetCurCity: false,
        preCity: [],
        // 搜索记录
        history: [],
        // 左右切换
        activeTab: 0,
        // 右
        mainActiveIndex: 0,
        activeId: 0,
        // 职业分类列表
        jobCategoryItems: [{
                text: '农业相关',
                badge: 10,
                children: [{
                        text: '育种',
                        id: 1,
                    },
                    {
                        text: '作物保护与检疫',
                        id: 2,
                    },
                    {
                        text: '粮食类生产与加工',
                        id: 3,
                    },
                    {
                        text: '蔬菜类生产与加工',
                        id: 4,
                    },
                    {
                        text: '水果类生产与加工',
                        id: 5,
                    },
                    {
                        text: '中草药栽培与加工',
                        id: 6,
                    },
                    {
                        text: '茶叶生产与加工',
                        id: 7,
                    },
                    {
                        text: '烟草栽培与加工',
                        id: 8,
                    },
                    {
                        text: '食用菌生产与加工',
                        id: 9,
                    },
                    {
                        text: '棉花栽培与加工',
                        id: 10,
                    },
                ],
            },
            {
                text: '林业相关',
                badge: 5,
                children: [{
                        text: '种子生产',
                        id: 1,
                    },
                    {
                        text: '林木育苗',
                        id: 2,
                    },
                    {
                        text: '病虫害防治',
                        id: 3,
                    },
                    {
                        text: '森林营造',
                        id: 4,
                    },
                    {
                        text: '经济林产品生产与加工',
                        id: 5,
                    },
                ],
            },
            {
                text: '畜牧业相关',
                badge: 8,
                children: [{
                        text: '育仔',
                        id: 1,
                    },
                    {
                        text: '动物防疫与检疫',
                        id: 2,
                    },
                    {
                        text: '动物饲养',
                        id: 3,
                    },
                    {
                        text: '蚕桑相关',
                        id: 4,
                    },
                    {
                        text: '肉类产品加工',
                        id: 5,
                    },
                    {
                        text: '蛋类产品加工',
                        id: 6,
                    },
                    {
                        text: '奶类产品加工',
                        id: 7,
                    },
                    {
                        text: '皮毛类产品加工',
                        id: 8,
                    },
                ],
            },
            {
                text: '渔业相关',
                badge: 5,
                children: [{
                        text: '育苗',
                        id: 1,
                    },
                    {
                        text: '保护与检疫',
                        id: 2,
                    },
                    {
                        text: '淡水渔类饲养',
                        id: 3,
                    },
                    {
                        text: '海洋鱼类加工',
                        id: 4,
                    },
                    {
                        text: '捕捞与加工',
                        id: 5,
                    },
                ],
            },
            {
                text: '机械与自动化相关',
                badge: 4,
                children: [{
                        text: '农业智能化装备应用',
                        id: 1,
                    },
                    {
                        text: '畜禽智能化装备应用',
                        id: 2,
                    },
                    {
                        text: '木业智能化装备应用',
                        id: 3,
                    },
                    {
                        text: '现代化系统设计（大型工程需谨慎）',
                        id: 4,
                    },
                ],
            },
            {
                text: '电商与运输',
                badge: 4,
                children: [{
                        text: '农副产品销售',
                        id: 1,
                    },
                    {
                        text: '休闲旅游推广',
                        id: 2,
                    },
                    {
                        text: '特色产业、产品宣传',
                        id: 3,
                    },
                    {
                        text: '客运',
                        id: 4,
                    },
                    {
                        text: '货运',
                        id: 5,
                    },
                    {
                        text: '招商引资代理',
                        id: 6,
                    },
                ],
            },
            {
                text: '服务业相关',
                badge: 5,
                children: [{
                        text: '酒店服务员',
                        id: 1,
                    },
                    {
                        text: '厨师',
                        id: 2,
                    },
                    {
                        text: '保洁',
                        id: 3,
                    },
                    {
                        text: '保安',
                        id: 4,
                    },
                    {
                        text: '导游',
                        id: 5,
                    },
                ],
            },
        ]
    },

    toDeleteSearchHistory() {
        let that = this
        wx.showModal({
            title: '提示',
            content: '确定要删除吗？',
            success: function (sm) {
                if (sm.confirm) {
                    that.setData({
                        history: []
                    })
                    wx.removeStorageSync('history-keywords')
                } else if (sm.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },

    // 获取当前位置信息
    getLocation() {
        if (this.data.isGetCurCity) {
            return
        }
        wx.getLocation({ // 获取当前位置
            type: 'gcj02' // gcj02火星坐标系，用于地图标记点位
        }).then(async res => { // 获取成功
            const {
                latitude,
                longitude
            } = res // 如果传入为空，则使用data内数据
            console.log("经纬度：" + longitude + ", " + latitude)
            await app.call({ // 发起云函数请求
                name: 'location', // 业务为location，获取经纬度信息
                data: { // 传入经纬度信息
                    location: `${latitude},${longitude}`
                },
                load: false // 不显示加载loading，静默执行
            }).then(res => {
                this.setData({
                    curCity: res.adinfo.split(',')[3],
                    // pickCity: res.adinfo.split(',')[3],
                    isGetCurCity: true
                })
                // 确定该位置所属区号
                this.confirmCurCityNum()
            })
        }).catch(e => {
            // 获取失败
            wx.showToast({
                title: '获取当前定位失败',
                icon: 'none'
            })
            setTimeout(() => {
                wx.hideToast()
            }, 800)
        })
    },

    // 确定地区所属区号
    confirmCurCityNum() {
        let obj = this.data.areaList.county_list
        let findKey = (value, compare = (a, b) => a === b) => {
            return Object.keys(obj).find(k => compare(obj[k], value))
        }
        const pickCityNum = findKey(this.data.pickCity)
        this.setData({
            curCityNum: pickCityNum
        })
    },

    // 点击搜索
    toSearchResultPage(e) {
        // console.log('toSearchResultPage', e.detail)
        if (e.detail) {
            this.data.history.unshift(e.detail)
            const history = [...new Set(this.data.history)]
            this.setData({
                history: history
            })
            wx.setStorageSync('history-keywords', history)
            wx.navigateTo({
                url: '/pages/search-result/search-result?keyword=' + e.detail + '&city=' + this.data.pickCity,
            })
            e.detail = ''
        } else {
            Toast.fail('输入为空~')
        }
    },

    // 点击搜索记录
    confirmSearch(e) {
        console.log(e.currentTarget.dataset.item)
        let keyword = e.currentTarget.dataset.item
        this.data.history.unshift(keyword)
        const history = [...new Set(this.data.history)]
        this.setData({
            history: history
        })
        wx.setStorageSync('history-keywords', history)
        wx.navigateTo({
            url: '/pages/search-result/search-result?keyword=' + keyword + '&city=' + this.data.pickCity,
        })
    },

    // 点击职业类型
    onClickNav({
        detail = {}
    }) {
        this.setData({
            mainActiveIndex: detail.index || 0,
        });
    },

    // 选择具体职业
    onClickItem({
        detail = {}
    }) {
        const activeId = this.data.activeId === detail.id ? null : detail.id;
        this.setData({
            activeId
        })

        this.data.history.unshift(detail.text)
        const history = [...new Set(this.data.history)]
        this.setData({
            history: history
        })
        wx.setStorageSync('history-keywords', history)
        wx.navigateTo({
            url: '/pages/search-result/search-result?keyword=' + detail.text + '&city=' + this.data.pickCity,
        })
    },

    // 切换左右
    onChangeTab(event) {
        this.setData({
            activeTab: event.detail.name
        })
    },

    // 回到左右
    backHome() {
        wx.switchTab({
            url: '/pages/home/home'
        })
    },

    // 选择城市
    confirmCity(e) {
        if (e.currentTarget.dataset.city) {
            this.setData({
                pickCity: e.currentTarget.dataset.city
            })
        } else {
            this.setData({
                pickCity: e.detail.values[2].name
            })
        }
        this.data.preCity.unshift(this.data.pickCity)
        const preCity = [...new Set(this.data.preCity)]
        this.setData({
            preCity: preCity
        })
        wx.setStorageSync('searchPrecity', this.data.preCity)
        this.onClose()
    },

    // 关闭操作框
    onClose() {
        this.setData({
            showCityPicker: false
        });
    },

    // 打开操作框
    toPickCity() {
        this.confirmCurCityNum()
        this.setData({
            showCityPicker: true
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getLocation()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        if (wx.getStorageSync('searchPrecity')) {
            this.setData({
                preCity: wx.getStorageSync('searchPrecity')
            })
        }
        if (wx.getStorageSync('history-keywords')) {
            this.setData({
                history: wx.getStorageSync('history-keywords')
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})